<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!--代码画线-->
    <canvas id="mycanvas" width="600px" height="400px" style="border: 1px solid pink;"></canvas>
    <!--鼠标画线-->
    <canvas id="drawcanvas" width="800px" height="500px" style="border: 1px solid pink;display: block;"></canvas>
</body>
</html>
    <script>
        //获取画布
        let  cav =document.querySelector("#mycanvas");
        //创建画笔
        let cxt = cav.getContext("2d");
        //绘制直线
        cxt.strokeStyle = "red";//线条样式
        cxt.setLineDash([10,5]);//10长度实线+5长度虚线
        cxt.moveTo(50,50);
        cxt.lineTo(100,100);
        cxt.stroke();
        cxt.beginPath();//重新创建路径，不同样式
        cxt.setLineDash([0]);//变为实线
        cxt.strokeStyle = "blue"
        cxt.lineWidth = 3;//粗细
        cxt.moveTo(100,100);
        cxt.lineTo(120,200);
        cxt.closePath();//封闭路径
        cxt.rect(0,0,200,200);//矩形绘制 strokeRect线描矩形不能有填充 fillRect填充矩形不能有边框 clearRect清除矩形（橡皮擦和清屏功能）
        cxt.arc(200,200,50,0,Math.PI*2,true);//原型绘制（x，y，半径，开始度数，结束度数，顺逆时针）右边为0度起始 扇形在圆形前使用moveTo定出圆心点
        cxt.stroke();
        cxt.save;//保存坐标系
        cxt.translate(200,200);//移动坐标顶点
        let draw = document.querySelector("#drawcanvas");
        let drawP = draw.getContext("2d");
        //消除偏差
        let offleft = draw.offsetLeft;
        let offtop = draw.offsetTop;
        drawP.strokeStyle = "#333333"
        draw.addEventListener("mousedown",function(e){
            drawP.moveTo(e.clientX-offleft,e.clientY-offtop);//获取起始点
            draw.onmousemove = function(e){
                drawP.lineTo(e.clientX-offleft,e.clientY-offtop);
                drawP.stroke();
            }
            draw.onmouseup = function(){
                draw.onmousemove = null;
            }
        });
        
    </script>